package admin.Controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import jxl.write.WriteException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import admin.DTO.ComponentDTO;
import admin.DTO.MachineDTO;
import admin.Service.ExcelService;
import admin.util.ExcelUtil;
import admin.util.JfreeChart;

@Controller
public class ExcelController {
	private ExcelService service;
	
	public ExcelController(ExcelService service){
		this.service = service;
	}
	
	@RequestMapping("/excel.do")
	public String excel(){
		return "excel.ex";
	}
	@RequestMapping("/componentKind.do")
	public ModelAndView componentKind(){
		ModelAndView mv = new ModelAndView();
		try {
			ArrayList<ComponentDTO> list = service.componentKind();
			mv.addObject("list", list);
			mv.setViewName("jsonView");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return mv;
	}
	
	@RequestMapping("/is_fault_N.do")
	public ModelAndView isFaultN(HttpServletRequest request,ComponentDTO dto){
		ModelAndView mv = new ModelAndView();
		String flag=request.getParameter("flag");
		try {
			ArrayList<ComponentDTO> list =service.isFaultN(dto);
			ComponentDTO cdto = service.count(dto);
			JfreeChart chart = new JfreeChart();
			ExcelUtil ex = new ExcelUtil();
			if(dto.getIs_fault().equals("N")){
				chart.Chart1(Integer.parseInt(cdto.getFaultcount()));
				ex.excel1(list);
			}else if(dto.getIs_fault().equals("Y")){
				chart.Chart2(Integer.parseInt(cdto.getFaultcount()));
				ex.excel2(list);
			}else {
				dto.setIs_fault("Y");
				ComponentDTO dto1=service.count(dto);
				dto.setIs_fault("N");
				ComponentDTO dto2 = service.count(dto1);
				chart.Chart3(Integer.parseInt(dto1.getFaultcount()),Integer.parseInt(dto2.getFaultcount()));
				ex.excel3(list);
			}
			mv.addObject("message", "엑셀을 저장하였습니다. \n 해당 폴더에서 확인해주세요");
			mv.setViewName("jsonView");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		return mv;
	}
	
	@RequestMapping("/machine_a.do")
	public ModelAndView machine(MachineDTO dto){
		ModelAndView mv = new ModelAndView();
		try {
			ArrayList<MachineDTO>list = service.machine(dto);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return mv;
	}
}
